<template>
  <div>
    <el-dialog
      :title="`${currentStudent.name || ''}的考试详情`"
      :visible.sync="visible"
      width="800px"
      @close="handleClose"
    >
      <div class="exam-detail-container">
        <div class="detail-section">
          <h3 class="section-title">基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="detail-item">
                <span class="item-label">姓名：</span>
                <span class="item-value">{{ currentStudent.name || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <span class="item-label">性别：</span>
                <span class="item-value">{{ currentStudent.gender || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="item-label">证件编号：</span>
                <span class="item-value">{{ currentStudent.idCard || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="item-label">联系电话：</span>
                <span class="item-value">{{ currentStudent.phone || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="detail-item">
                <span class="item-label">单位名称：</span>
                <span class="item-value">{{ currentStudent.company || '-' }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="detail-section">
          <h3 class="section-title">考试状态</h3>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="detail-item">
                <span class="item-label">考试状态：</span>
                <span class="item-value">{{ currentStudent.examStatus || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="detail-item">
                <span class="item-label">考试次数：</span>
                <span class="item-value">{{ currentStudent.examTimes || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="detail-item">
                <span class="item-label">考试成绩：</span>
                <span class="item-value">{{ currentStudent.examScore || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="detail-item">
                <span class="item-label">是否通过：</span>
                <span class="item-value" :style="{ color: currentStudent.isPass === '通过' ? 'green' : 'red' }">
                  {{ currentStudent.isPass || '-' }}
                </span>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="detail-section">
          <h3 class="section-title">补考信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="item-label">补考情况：</span>
                <span class="item-value">{{ currentStudent.makeupExam || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="item-label">补考标记：</span>
                <span class="item-value">{{ currentStudent.makeupMark || '-' }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="detail-section">
          <h3 class="section-title">考试记录</h3>
          <el-table
            :data="examRecords"
            border
            size="small"
            style="width: 100%;"
          >
            <el-table-column prop="examDate" label="考试日期" />
            <el-table-column prop="score" label="成绩" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <span :style="{ color: scope.row.status === '通过' ? 'green' : 'red' }">
                  {{ scope.row.status }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  type="text"
                  @click="openExamPaperDialog(scope.row)"
                  size="small"
                >
                  查看考卷
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="detail-section">
          <h3 class="section-title">备注信息</h3>
          <el-row :gutter="20">
            <el-col :span="24">
              <div class="detail-item">
                <span class="item-label">备注内容：</span>
                <span class="item-value">{{ currentStudent.remark || '无' }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <div style="margin-top: 20px; text-align: center;">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 考卷详情弹窗 -->
    <el-dialog
      title="考卷详情"
      :visible.sync="examPaperDialogVisible"
      width="90%"
      max-height="80vh"
      :close-on-click-modal="false"
    >
      <div class="exam-paper-container">
        <div class="questions-container">
          <div
            class="question-item"
            v-for="(question, index) in currentExamPaper.questions"
            :key="question.questionId"
          >
            <div class="question-header">
              <span class="question-index">{{ index + 1 }}.</span>
              <span class="question-type">
                {{ getQuestionType(question.questionType) }}
              </span>
            </div>
            <div class="question-content">
              {{ question.questionName }}
            </div>

            <div v-if="question.questionOptionList && question.questionOptionList.length > 0" class="question-options">
              <div
                class="option-item"
                v-for="option in question.questionOptionList"
                :key="option.optionId"
                :class="{
                  'correct-option': option.optionName === question.answer,
                  'student-option': option.optionName === question.studentAnswer
                }"
              >
                <span class="option-label">{{ option.optionName }}.</span>
                <span class="option-content">{{ option.optionContent }}</span>
              </div>
            </div>

            <div class="question-answer">
              <div class="answer-label">参考答案: {{ question.answer || '无' }}</div>
              <div v-if="question.studentAnswer" class="student-answer">
                你的答案: {{ question.studentAnswer }}
              </div>
              <div v-if="question.analysisContent" class="answer-analysis">
                解析: {{ question.analysisContent }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="examPaperDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getExamRecordInfo } from "@/api/examination/examRecord";
import { getExamListByClassId } from "@/api/examination/examRecord";

export default {
  name: "ExamDetailDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    studentId: {
      type: [String, Number],
      required: true
    },
    classId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      currentStudent: {},
      examRecords: [],
      examPaperDialogVisible: false,
      currentExamPaper: {
        examNo: '',
        examDate: '',
        score: '',
        questions: []
      }
    };
  },
  watch: {
    // visible(newVal) {
    //   if (newVal) {
    //     this.loadStudentInfo();
    //     this.loadExamRecords();
    //   }
    // },
    // studentId(newVal) {
    //   if (this.visible) {
    //     this.loadStudentInfo();
    //     this.loadExamRecords();
    //   }
    // },
    classId(newVal) {
      if (this.visible && this.studentId) {
        this.loadExamRecords();
      }
    }
  },
  methods: {
    async loadStudentInfo() {
      try {
        const res = await getExamListByClassId({
          trainingClassId: this.classId,
          studentId: this.studentId,
          pageNum: 1,
          pageSize: 1
        });

        if (res.code === 200 && Array.isArray(res.rows) && res.rows.length > 0) {
          const item = res.rows[0];
          this.currentStudent = {
            id: item.studentId || "-",
            name: item.studentName || "-",
            idCard: item.idNumber || "-",
            gender: item.sex  || "-",
            phone: item.phonenumber || "-",
            company: item.unitName || "-",
            examStatus: item.examStatus || "-",
            examTimes: item.examFrequency || "0",
            examScore: item.totalScore || "",
            isPass: item.examResult || "",
            makeupExam: item.makeUpStatus || "-",
            makeupMark: item.makeUpMark || "-",
            remark: item.examRecordRemark || ""
          };
        }
      } catch (error) {
        this.$message.error("加载学员信息失败");
        console.error("加载学员信息错误:", error);
      }
    },
    async loadExamRecords() {
      try {
        const res = await getExamRecordInfo({
          studentId: this.studentId,
          trainingClassId: this.classId
        });

        if (res.code === 200 && Array.isArray(res.rows) && res.rows.length > 0) {
          this.examRecords = res.rows.map(record => ({
            examNo: record.examNumber || `K${record.createTime.split(' ')[0].replace(/-/g, '')}${record.studentId.slice(-6)}`,
            examDate: record.createTime ? record.createTime.split(' ')[0] : '',
            score: record.totalScore || '0',
            status: this.getExamStatus(record.examResult, record.theoryResult),
            originalRecord: record
          }));
        } else {
          this.examRecords = [];
          this.$message.warning('未查询到考试记录');
        }
      } catch (error) {
        this.$message.error('加载考试记录失败');
        console.error('加载考试记录错误:', error);
        this.examRecords = [];
      }
    },
    openExamPaperDialog(record) {
      this.currentExamPaper = {
        examNo: record.examNo,
        examDate: record.examDate,
        score: record.score,
        questions: record.originalRecord.examRecordInfoDtoList || []
      };
      this.examPaperDialogVisible = true;
    },
    getExamStatus(examResult, theoryResult) {
      if (examResult === '通过' || examResult === '0') return '通过';
      if (examResult === '未通过' || examResult === '1') return '未通过';
      if (theoryResult === '0') return '通过';
      if (theoryResult === '1') return '未通过';
      return '待评价';
    },
    getQuestionType(type) {
      const typeMap = {
        '1': '单选题',
        '2': '多选题',
        '3': '判断题'
      };
      return typeMap[type] || `题型${type}`;
    },
    handleClose() {
      this.$emit('update');
      this.currentStudent = {};
      this.examRecords = [];
      this.currentExamPaper = { questions: [] };
      this.examPaperDialogVisible = false;
    }
  }
};
</script>

<style scoped>
.exam-detail-container {
  padding: 10px 0;
}
.detail-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #eee;
}
.detail-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}
.section-title {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #303133;
  padding-left: 5px;
  border-left: 3px solid #409eff;
}
.detail-item {
  margin-bottom: 12px;
  line-height: 1.8;
}
.item-label {
  display: inline-block;
  color: #606266;
  width: 100px;
  font-weight: 500;
}
.item-value {
  color: #303133;
}

.exam-paper-container {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.questions-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.question-item {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-weight: 500;
}

.question-index {
  margin-right: 10px;
  color: #409eff;
}

.question-type {
  font-size: 13px;
  color: #67c23a;
  background-color: rgba(103, 194, 58, 0.1);
  padding: 2px 8px;
  border-radius: 12px;
  margin-left: 10px;
}

.question-content {
  margin-bottom: 10px;
  line-height: 1.6;
}

.question-options {
  margin: 10px 0 15px 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 5px 10px;
  border-radius: 4px;
}

.option-label {
  min-width: 20px;
  margin-right: 10px;
  font-weight: 500;
}

.correct-option {
  background-color: rgba(103, 194, 58, 0.1);
  border-left: 3px solid #67c23a;
}

.student-option {
  background-color: rgba(64, 158, 255, 0.1);
  border-left: 3px solid #409eff;
}

.question-answer {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #eee;
  font-size: 14px;
}

.answer-label {
  color: #67c23a;
  margin-bottom: 5px;
}

.student-answer {
  color: #409eff;
  margin-bottom: 5px;
}

.answer-analysis {
  color: #f56c6c;
  margin-top: 5px;
  padding: 5px 10px;
  background-color: rgba(245, 108, 108, 0.1);
  border-radius: 4px;
}
</style>
